from flask import Blueprint, request, jsonify, render_template
from flask_login import login_required
from app import db
from app.models.user import User
from app.models.objective import Objective
from app.models.project import Project
from app.utils.decorators import admin_required

bp = Blueprint('admin', __name__, url_prefix='/api/admin')

@bp.route('/users', methods=['GET'])
@admin_required
def get_all_users():
    """获取所有用户"""
    users = User.query.all()
    return jsonify([user.to_dict() for user in users]), 200

@bp.route('/users/<int:id>', methods=['GET'])
@admin_required
def get_user(id):
    """获取单个用户详情"""
    user = User.query.get_or_404(id)
    return jsonify(user.to_dict(include_sensitive=True)), 200

@bp.route('/users/<int:id>', methods=['PUT'])
@admin_required
def update_user(id):
    """更新用户信息"""
    user = User.query.get_or_404(id)
    data = request.get_json()

    updatable_fields = ['username', 'email', 'full_name', 'role', 'department', 'manager_id']
    for field in updatable_fields:
        if field in data:
            setattr(user, field, data[field])

    if 'password' in data:
        user.set_password(data['password'])

    db.session.commit()
    return jsonify(user.to_dict()), 200

@bp.route('/users/<int:id>', methods=['DELETE'])
@admin_required
def delete_user(id):
    """删除用户"""
    user = User.query.get_or_404(id)

    # 检查是否有关联数据
    if user.objectives.count() > 0 or user.projects.count() > 0:
        return jsonify({
            'error': 'Cannot delete user with associated objectives or projects',
            'objectives_count': user.objectives.count(),
            'projects_count': user.projects.count()
        }), 409

    db.session.delete(user)
    db.session.commit()
    return jsonify({'message': 'User deleted successfully'}), 200

@bp.route('/stats', methods=['GET'])
@admin_required
def get_system_stats():
    """获取系统统计信息"""
    stats = {
        'users': {
            'total': User.query.count(),
            'admins': User.query.filter_by(role='admin').count(),
            'managers': User.query.filter_by(role='manager').count(),
            'employees': User.query.filter_by(role='employee').count()
        },
        'objectives': {
            'total': Objective.query.count(),
            'active': Objective.query.filter_by(status='active').count(),
            'completed': Objective.query.filter_by(status='completed').count(),
            'by_level': {
                'company': Objective.query.filter_by(level='company').count(),
                'department': Objective.query.filter_by(level='department').count(),
                'individual': Objective.query.filter_by(level='individual').count()
            }
        },
        'projects': {
            'total': Project.query.count(),
            'active': Project.query.filter_by(status='active').count(),
            'completed': Project.query.filter_by(status='completed').count()
        }
    }

    return jsonify(stats), 200

@bp.route('/init-db', methods=['POST'])
@admin_required
def initialize_database():
    """初始化数据库（创建示例数据）"""
    # 检查是否已有数据
    if User.query.count() > 1:  # 除了当前管理员
        return jsonify({'error': 'Database already initialized'}), 409

    # 创建示例用户
    manager1 = User(
        username='manager1',
        email='manager1@company.com',
        full_name='张主管',
        role='manager',
        department='技术部'
    )
    manager1.set_password('password123')
    db.session.add(manager1)

    employee1 = User(
        username='employee1',
        email='employee1@company.com',
        full_name='李员工',
        role='employee',
        department='技术部'
    )
    employee1.set_password('password123')
    db.session.add(employee1)

    db.session.commit()

    # 设置员工的主管
    employee1.manager_id = manager1.id
    db.session.commit()

    return jsonify({
        'message': 'Database initialized with sample data',
        'users_created': 2
    }), 201